// shopMallPackage/pages/myOrderList/myOrderList.js
import { getMyOrderList, payAgainAction, cancelOneOrder, sureReciveProduct, applyQuitProduct } from '../../../service/onetoone_service'

import {
  queryOrderList,
  getOrderCategoryNums,
  cancelOrder,
  delOrder,
  orderPay,
  confirmOrderReceive,
} from "../../../service/jb_order_service"
import {
  HOMETOPBG_IMG,
} from "../../../service/image_service"
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    homeTopBg_img: HOMETOPBG_IMG,
    menuTop: app.globalData.menuButton.top,
    menuHeight: app.globalData.menuButton.height,
    orderStatus: 0,
    realStatus: 0,
    page: 1,
    pageSize: 200,
    orderTab: [
      {
        name: "待支付",
        key: 0,
        num: 0,
      },
      {
        name: "待发货",
        key: 1,
        num: 0,
      },
      {
        name: "待收货",
        key: 2,
        num: 0,
      },
      {
        name: "待评价",
        key: 3,
        num: 0,
      },
      {
        name: "已完成",
        key: 4,
        num: 0,
      },

    ],
    dataList: [

    ],
    orderNums: {
      "completeCount": 0,//已完成
      "evaluatedCount": 0,//待评价
      "orderCount": 0,//订单数量
      "receivedCount": 0,//待收货
      "refundCount": 0,//退款数量
      "sumPrice": "0",//订单消费总额
      "unPaidCount": 0,//待支付
      "unShippedCount": 0,//待发货
    },
    showLogPop: false,
    selectOrderData: {},
    isShowLoading: false,//加载状态出现
    isBottomShow: false,//是否没有更多数据了
    refreshFlag: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.type) {
      this.setData({
        orderStatus: options.type,
        realStatus: options.type
      })
    }
    this.getMyOrderList();
    this.getOrderCategoryNums();
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  switchAction(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      orderStatus: index,
      realStatus: e.currentTarget.dataset.status,
      page: 1,
      dataList: [],
    })
    this.getMyOrderList();
  },
  getMyOrderList(type) {
    wx.showLoading();
    queryOrderList(this.data.realStatus, this.data.page).then(res => {
      console.log("JJLog:我的订单列表===:" + JSON.stringify(res));
      wx.hideLoading();
      // res = {
      //   "code": 200,
      //   "message": "操作成功",
      //   "data": {
      //     "page": 1,
      //     "limit": 20,
      //     "totalPage": 1,
      //     "total": 1,
      //     "list": [{
      //       "storeOrder": null,
      //       "cartInfo": null,
      //       "statusPic": null,
      //       "offlinePayStatus": null,
      //       "id": 23,
      //       "orderId": "order35009170519795072492445",
      //       "createTime": "2024-01-14 10:05:50",
      //       "paid": true,
      //       "payTime": null,
      //       "payPrice": "787.00",
      //       "status": 1,
      //       "orderStatus": "待收货",
      //       "totalNum": 1,
      //       "payPostage": "0.00",
      //       "refundStatus": 0,
      //       "deliveryName": null,
      //       "deliveryType": null,
      //       "deliveryId": null,
      //       "pinkId": 0,
      //       "bargainId": 0,
      //       "verifyCode": "",
      //       "storeId": 0,
      //       "shippingType": 1,
      //       "activityType": "普通",
      //       "orderInfoList": [{
      //         "attrId": null,
      //         "productId": 8,
      //         "cartNum": 1,
      //         "image": "images/public/maintain/2021/12/25/7a6475bba07c47bb98e5db0e0d21c8ebq5sw2kijlc.jpg",
      //         "storeName": "兰蔻（LANCOME）口红196 全新菁纯丝绒雾面唇膏 化妆品礼盒",
      //         "price": "787.00",
      //         "isReply": null,
      //         "sku": null
      //       }],
      //       "type": 0
      //     }]
      //   }
      // }
      if (res.code == 200 && res.data) {
        let arr = (type == 'refresh' ? [] : this.data.dataList || []);
        arr = arr.concat(res.data.list || [])
        this.setData({
          dataList: arr,
          refreshFlag: false,
          isShowLoading: false,
          isBottomShow: res.data.totalPage == this.data.page ? true : false,
        })

      } else {
        this.setData({
          dataList: []
        })
      }
    }).catch(err => {
      wx.hideLoading();
      this.setData({
        refreshFlag: false,
      })
      if (this.data.page != 1) {
        this.setData({
          page: this.data.page - 1
        })
      }
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
      console.error("JJLog:queryOrderList", err);
    })
  },
  //获取对应订单分类数量
  getOrderCategoryNums() {
    getOrderCategoryNums().then(res => {
      if (res.code == 200) {
        this.setData({
          orderNums: res.data
        })
        this.dealOrderNumShow(res.data)
      }
    }).catch(err => {
      console.error("JJLog:getOrderCategoryNums", err);
    })
  },
  dealOrderNumShow(orderData) {
    let arr = this.data.orderTab;
    arr[0].num = orderData.unPaidCount || 0
    arr[1].num = orderData.unShippedCount || 0
    arr[2].num = orderData.receivedCount || 0
    arr[3].num = orderData.evaluatedCount || 0
    arr[4].num = orderData.completeCount || 0
    this.setData({
      orderTab: arr
    })
  },

  // 申请退款操作:
  applyQuitAction(e) {
    let orderData = e.detail;
    wx.showModal({
      title: '提示',
      content: '确认申请退款?',
      success: res => {
        if (res.confirm) {
          wx.showLoading();
          applyQuitProduct(orderData.orderId).then(res => {
            // console.log("JJLog:我的订单列表===:" + JSON.stringify(res));
            wx.hideLoading();
            if (res.code == 200) {
              wx.showToast({
                title: '申请成功',
                icon: "none"
              })
              this.getMyOrderList('refresh');
            }
          }).catch(err => {
            wx.hideLoading();
            wx.showToast({
              title: err || "申请失败",
              icon: "none"
            })
            console.error("JJLog:applyQuitProduct", err);
          })
        }
      }
    })

  },


  //确认收货:
  sureGoodsAction(e) {
    let orderData = e.detail.orderData;
    let index = e.detail.index;
    wx.showModal({
      title: '提示',
      content: '确认当前订单已收到?',
      confirmColor: "#ff0000",
      cancelColor: "#c7c7c7",
      success: res => {
        if (res.confirm) {
          wx.showLoading();
          confirmOrderReceive(orderData.id).then(res => {
            // console.log("JJLog:我的订单列表===:" + JSON.stringify(res));
            wx.hideLoading();
            if (res.code == 200) {
              wx.showToast({
                title: '确认成功',
                icon: "none"
              })
              let arr = this.data.dataList;
              arr.splice(index, 1);
              this.setData({
                dataList: arr
              })
              this.getOrderCategoryNums()
            }
          }).catch(err => {
            wx.hideLoading();
            wx.showToast({
              title: err || "收货失败",
              icon: "none"
            })
            console.error("JJLog:sureReciveProduct", err);
          })
        }
      }
    })

  },

  //刷新订单列表
  handleRefresh() {
    this.setData({
      page: 1,
      refreshFlag: true,
      isBottomShow: false,
    })
    this.getMyOrderList('refresh')
  },
  //加载更多数据
  handleLoadmore() {
    if (this.data.isBottomShow) {
      return;
    }
    this.setData({
      page: this.data.page + 1,
      isShowLoading: true,
    })
    this.getMyOrderList();
  },

  // 查看物流信息:
  seeLogAction(e) {
    console.log("JJLog:没起作用");
    let orderData = e.detail;
    this.setData({
      selectOrderData: orderData,
      showLogPop: true,
    })
  },
  // 复制物流单号
  copyLogNumberAction() {
    wx.setClipboardData({
      data: this.data.selectOrderData.deliveryId,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制物流单号成功',
              icon: "none"
            })
          },
          fail: function (err) {
            wx.showToast({
              title: '复制失败',
              icon: "none"
            })
          }
        })
      }
    })
  },


  //取消订单:
  cancelOrderAction(e) {
    console.log("JJLog:点击取消:" + JSON.stringify(e));
    let orderData = e.detail.orderData;
    let index = e.detail.index;
    wx.showModal({
      title: '提示',
      content: '确认取消当前订单?',
      confirmColor: "#ff0000",
      success: res => {
        if (res.confirm) {
          wx.showLoading();
          cancelOrder({ id: orderData.id }).then(res => {
            // console.log("JJLog:我的订单列表===:" + JSON.stringify(res));
            wx.hideLoading();
            if (res.code == 200) {
              wx.showToast({
                title: '取消成功',
                icon: "none"
              })
              let arr = this.data.dataList;
              arr.splice(index, 1);
              this.setData({
                dataList: arr
              })
              this.getOrderCategoryNums()
            }
          }).catch(err => {
            wx.hideLoading();
            wx.showToast({
              title: err || "取消失败",
              icon: "none"
            })
            console.error("JJLog:cancelOneOrder", err);
          })
        }
      }
    })
  },

  //删除订单:
  deleteOrder(e) {
    console.log("JJLog:点击删除:" + JSON.stringify(e));
    let orderData = e.detail.orderData;
    let index = e.detail.index;
    wx.showModal({
      title: '提示',
      content: '确认删除当前订单?',
      success: res => {
        if (res.confirm) {
          wx.showLoading();
          delOrder({ id: orderData.id }).then(res => {
            // console.log("JJLog:我的订单列表===:" + JSON.stringify(res));
            wx.hideLoading();
            if (res.code == 200) {
              wx.showToast({
                title: '删除成功',
                icon: "none"
              })
              let arr = this.data.dataList;
              arr.splice(index, 1);
              this.setData({
                dataList: arr
              })
              this.getOrderCategoryNums()
            }
          }).catch(err => {
            wx.hideLoading();
            wx.showToast({
              title: err || "删除失败",
              icon: "none"
            })
            console.error("JJLog:delOrder", err);
          })
        }
      }
    })
  },
  // 立即付款
  payAgain(e) {
    let orderData = e.detail;

    let requestData = {
      orderNo: orderData.porderId,
      payChannel: "weixinh5",
      payType: "weixin",
      scene: 0
    }

    wx.showLoading({
      title: '支付中...',
    })

    orderPay(requestData).then(res => {
      console.log("JJLog:支付回调:" + JSON.stringify(res));
      if (res.code == 200) {

        console.log("JJLog:这里没来")
        let payData = res.data.jsConfig;
        wx.requestPayment({
          timeStamp: payData.timeStamp,
          nonceStr: payData.nonceStr,
          package: payData.packages,
          signType: 'MD5',
          paySign: payData.paySign,
          success: (res) => {
            wx.hideLoading();
            console.log("JJLog:微信支付成功回调:" + JSON.stringify(res));
            wx.showToast({
              title: '支付成功',
              icon: "success",
              duration: 2000
            })
            this.getMyOrderList('refresh');

          },
          fail: (err) => {
            wx.hideLoading();
            wx.showToast({
              title: '支付失败',
              icon: "none"
            })
            console.log("JJLog:微信支付失败回调:" + JSON.stringify(err));
          }
        });
      }
    }).catch(err => {
      console.error("JJLog购买商品失败:" + JSON.stringify(err));
      wx.hideLoading();
      wx.showToast({
        title: err || "支付失败",
        icon: "none"
      })
    })
  },
  clickCenterPopupOverlay() {
    this.setData({
      showLogPop: false,
    })
  },
})